package com.example.utils.httpServer;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;

/**
 * @Description: 解析请求体和相应体
 * @Author runto
 * @Date 2023/10/14 0:00
 * @PackageName:com.example.utils.httpServer
 * @ClassName: HttpServerUtil
 * @Version 1.0
 */
public class HttpServerUtil {
    /**
     * 从流中解析数据
     * @param request
     * @param response
     * @return
     */
    public static String reader(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            StringBuffer msg = new StringBuffer();
            String line = null;
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                msg.append(line);
            }
            return msg.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断空值
     */
    public static String getValue(JSONObject json, String key){
        String result = "";
        try {
            result = json.getString(key);
        } catch (Exception e) {
            result = "";
        }
        return result;
    }
}
